package com.tty.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tty.annotation.SysLog;
import com.tty.constant.UrlConstant;
import com.tty.entity.Result;
import com.tty.entity.Url;
import com.tty.entity.User;
import com.tty.enumerate.Msg;
import com.tty.mapper.StatMapper;
import com.tty.mapper.UrlMapper;
import com.tty.service.StatService;
import com.tty.service.UrlService;
import com.tty.service.UserService;
import com.tty.utils.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.DateUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

@Controller
public class UrlController {

    int a = 1;

    @Autowired
    UrlService urlService;

    @Autowired
    UserService userService;

    @Autowired
    StatService statService;

    @Autowired
    StatMapper statMapper;

    @Autowired
    UrlMapper urlMapper;
    @GetMapping("/admin1")
    public String admin(Model model){

        List<Url> allUrl = urlService.findAll();
        model.addAttribute("allUrl",allUrl);
        return "admin";
    }

    @PostMapping("/createUrl")
    @ResponseBody
    public String createUrl(String longUrl, HttpServletRequest request){
        JSONObject json = new JSONObject();

        String[] parts = longUrl.split("\r|\n");


        HttpSession session = request.getSession();

        User user = (User) session.getAttribute("user");



        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < parts.length; i++) {

            //使用parts[i] 从tbl_url 找出有没有对应的记录
//            Date createdTimeStat = statService.getCreatedTimeStat(parts[i]);
            Date lastVisitedStat = statMapper.getUrlByOriginUrlAndMaxLastVisited(parts[i]);

            Boolean res = false;

            if (Objects.isNull(user)){
                //访客逻辑

                Url url = new Url();
                url.setOriginUrl(parts[i]);
                url.setShortUrlId(UrlUtils.generateRandomCode(6));

                //在tbl_url 插入新数据
                res = urlService.insert(url);

                System.out.println(res);
                //构建短链接
                if (request.getServerPort() == 80 || request.getServerPort() == 443){
                    //http://主机名字/前缀/shortUrlId, http://localhost/a3B48/6eIcfh
                    sb.append(String.format("%s://%s/%s/%s<br>", request.getScheme(), request.getServerName(),
                            UrlConstant.TRIAL, url.getShortUrlId()));
                }else{

                    //http://主机名字/前缀/shortUrlId, http://localhost:8080/a3B48/6eIcfh
                    sb.append(String.format("%s://%s:%s/%s/%s<br>", request.getScheme(), request.getServerName(), request.getServerPort(),
                            UrlConstant.TRIAL, url.getShortUrlId()));
                }
                json.put("urlRes", new Result(sb.toString(), res, res ? Msg.CREATE_SUC : Msg.CREATE_FAIL));

            }else{
                //用户逻辑
                Url url = new Url();
                url.setUserId(user.getId());
                url.setOriginUrl(parts[i]);
                url.setShortUrlId(UrlUtils.generateRandomCode(6));

                //在tbl_url 插入新数据
                res = urlService.insert(url);

                //构建短链接
                if (request.getServerPort() == 80 || request.getServerPort() == 443){
                    //http://主机名字/前缀/shortUrlId, http://localhost/a3B48/6eIcfh
                    sb.append(String.format("%s://%s/%s/%s<br>", request.getScheme(), request.getServerName(),
                            user.getSeparate(), url.getShortUrlId()));
                }else{

                    //http://主机名字/前缀/shortUrlId, http://localhost:8080/a3B48/6eIcfh
                    sb.append(String.format("%s://%s:%s/%s/%s<br>", request.getScheme(), request.getServerName(), request.getServerPort(),
                            user.getSeparate(), url.getShortUrlId()));
                }

            }

//            if (!Objects.isNull(createdTimeStat)){
//                sb.append(String.format("该链接最后一次被转换的时间是%s<br>", DateUtils.format(createdTimeStat, "yyyy-MM-dd HH:mm:ss", Locale.CHINA)));
//            }

            if (!Objects.isNull(lastVisitedStat)){
                sb.append(String.format("该链接产生的短链接最后一次被访问的时间是%s<br>", DateUtils.format(lastVisitedStat, "yyyy-MM-dd HH:mm:ss", Locale.CHINA)));
            }

            json.put("urlRes", new Result(sb.toString(), res, res ? Msg.CREATE_SUC : Msg.CREATE_FAIL));
        }

        return json.toJSONString();
    }

    @SysLog("控制层: 以短链接访问")
    @GetMapping("{separate}/{shortUrlId}")
    public String visit(@PathVariable String separate, @PathVariable String shortUrlId, HttpServletResponse response) throws IOException {

        //检查链接是否合法
        //用separate取得User 对象
        User user = userService.getUserBySeparate(separate);

        if (Objects.isNull(user) && !UrlConstant.TRIAL.equals(separate)){
            return "noPage";
        }else {
            //separate合法
            //用shortUrlId 找到原始链接, 并且重定向
            Url url = urlService.getUrlByShortUrlId(shortUrlId);
            if (Objects.isNull(url)){
                return "noPage";
            }else{
                response.sendRedirect(url.getOriginUrl());
                LambdaQueryWrapper<Url> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Url::getShortUrlId,shortUrlId);
                Url url1 = new Url();
                url1.setVisits(a);
                url1.setLastVisited(new Date());
                urlMapper.update(url1,wrapper);
                a++;
            }
        }

        return "noPage";
    }

}
